/**
 * @file
 * @author LiQun
 * @date 2021/11/28
 */
const fs = require('fs-extra');
const path = require('path');
const inquirer = require('inquirer');

const execa = require('execa');

const {checkInstall, clone} = require('../../utils/git');
const {getActiveProjectInfo} = require('../../utils/utils');

const http = require('../../utils/http');

async function projectInit(answers) {
  const useGit = answers['useGit'];
  const cloneCode = answers['cloneCode'];
  const gitPath = answers['gitPath'];
  const branch = answers['branch'];
  const projectPath = answers['projectPath'];
  const projectName = answers['projectName'];
  const buildOutputDir = answers['buildOutputDir'];


  if (!useGit) {
    console.log('未使用git,请后续自行放置代码到项目路径下!');
  }
  if (useGit && !cloneCode) {
    console.log('未允许拉取git代码,请后续自行拉取git代码!');
  }
  if (useGit && cloneCode) {
    await checkInstall()
    await clone(gitPath, branch, projectPath);
  }
  // 保存项目信息
  const data = {
    projectName,
    projectPath: answers.projectPath,
    gitPath,
    buildOutputDir
  }
  const projectInfoList = projectList() || [];
  projectInfoList.unshift(data);
  fs.writeFileSync(path.resolve(__dirname, '../../cache/project.json'), JSON.stringify(projectInfoList, null, 4), 'utf8');
}

module.exports.projectInit = projectInit;

function projectList() {
  const projectInfoPath = path.resolve(__dirname, '../../cache/project.json');
  let exists = fs.existsSync(projectInfoPath);
  let result = [];
  if (!exists) {
    fs.writeFileSync(projectInfoPath, '[]', 'utf8');
  } else {
    const data = fs.readFileSync(projectInfoPath);
    result = JSON.parse(data);
  }
  return result;
}

module.exports.projectList = projectList;

async function preview() {
  let lastProjectInfo = getActiveProjectInfo();
  if (!lastProjectInfo) {
    console.log('未获取到项目信息!');
    return;
  }
  const projectPath = lastProjectInfo.projectPath;
  // 读取项目下是否存在package.json
  const pkg = projectPath + '/' + 'package.json';
  console.log('pkg', pkg);
  if (fs.existsSync(pkg)) {
    let data = fs.readFileSync(pkg);
    data = JSON.parse(data);
    const scripts = data.scripts || {};
    if (Object.keys(scripts).length > 0) {

      const answers = await inquirer.prompt([
        {
          type: 'list',
          message: `请选择要执行的编译命令:`,
          name: 'script',
          choices: Object.keys(scripts),
          default: ''
        },
      ])
      console.log('answers', answers);
      const {script} = answers;
      console.log('正在编译项目...');
      await execa("npm", ['run', script], {
        cwd: projectPath,
        async: true
      });
      console.log('编译完成!');
      // 预览
      const buildOutputDir = lastProjectInfo.buildOutputDir;
      // 预览
      await http.get(`/v2/preview?project=${projectPath}&qr-format=terminal&qr-size=small`)
    }
  }
}

module.exports.preview = preview;


function upload() {

}

module.exports.upload = upload;


function clear() {

}

module.exports.upload = clear;
